package com.thlws.rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/***
 * 通配符模式 ,官方叫 Topic
 * BuiltinExchangeType.TOPIC
 * 本质是消费端对 bindingKey 的模糊匹配
 * @author HanleyTang
 *
 */
public class Consumter {
	
	private static final String EXCHANGE_NAME = "topic_x";

	public static void main(String[] args) throws Exception{
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("116.228.212.36");
		factory.setUsername("hanley");
		factory.setPassword("hanley");
		factory.setVirtualHost("/test");
		
	    Connection connection = factory.newConnection();
	    Channel channel = connection.createChannel();

	    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
	    String queueName = channel.queueDeclare().getQueue();

	    //注意模糊匹配在消费端进行,发送到仍旧是明确的,比如cms.error.log
	    //Erlang 中匹配规则中 #表示所有,*表示一个
	    //#.error.* 可匹配  aa.bb.cc.error.log,无法匹配aa.bb.cc.error.log.1
	    String bindingKey = "#.error.*";
	    channel.queueBind(queueName, EXCHANGE_NAME, bindingKey);

	    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
	        String message = new String(delivery.getBody(), "UTF-8");
	        System.out.println(" [x] Received '" +
	            delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
	    };
	    channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });

	}

}
